package cn.lzy.web.admin;

import cn.lzy.model.ResponseData.ArticleResponseData;
import cn.lzy.model.ResponseData.StaticticsBo;
import cn.lzy.model.domain.Article;
import cn.lzy.model.domain.Comment;
import cn.lzy.service.IArticleService;
import cn.lzy.service.ICommentService;
import cn.lzy.service.ISiteService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: WeiKaiYe
 * @CreateTime: 2023-11-01  00:51
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private ISiteService siteServiceImpl;
    @Autowired
    private IArticleService articleServiceImpl;
    @Autowired
    private ICommentService CommentServiceImpl;


    // 管理中心起始页
    @GetMapping(value = {"", "/index"})
    public String index(HttpServletRequest request) {
        // 获取最新的15篇博客、评论以及统计数据
        List<Article> articles = siteServiceImpl.recentArticles(10);
        List<Comment> comments = siteServiceImpl.recentComments(10);
        StaticticsBo staticticsBo = siteServiceImpl.getStatistics();
        // 向Request域中存储数据
        request.setAttribute("comments", comments);
        request.setAttribute("articles", articles);
        request.setAttribute("statistics", staticticsBo);
        return "back/index";
    }

    // 向文章发表页面跳转
    @GetMapping(value = "/article/toEditPage")
    public String newArticle() {
        return "back/article_edit";//跳转页面
    }

    // 发表文章
    @PostMapping(value = "/article/publish")//点击发表会跳转到此路径
    @ResponseBody
    public ArticleResponseData publishArticle(Article article) {
        if (StringUtils.isBlank(article.getCategories())) {
            article.setCategories("默认分类");
        }
        try {
            articleServiceImpl.publish(article);//调用articleServiceImpl.publish（）方法来保存文章到数据库
            logger.info("文章发布成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("文章发布失败，错误信息: " + e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    // 跳转到后台文章列表页面
    @GetMapping(value = "/article")
    public String index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "count", defaultValue = "10") int count,
                        HttpServletRequest request) {
        PageInfo<Article> pageInfo = articleServiceImpl.selectArticleWithPage(page, count);
        request.setAttribute("articles", pageInfo);
        return "back/article_list";
    }

    // 向文章修改页面跳转
    @GetMapping(value = "/article/{id}")
    public String editArticle(@PathVariable("id") String id, HttpServletRequest request) {
        Article article = articleServiceImpl.selectArticleWithId(Integer.parseInt(id));
        request.setAttribute("contents", article);
        request.setAttribute("categories", article.getCategories());
        return "back/article_edit";
    }

    // 文章修改处理
    @PostMapping(value = "/article/modify")
    @ResponseBody
    public ArticleResponseData modifyArticle(Article article) {
        try {
            articleServiceImpl.updateArticleWithId(article);
            logger.info("文章更新成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("文章更新失败，错误信息: " + e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    //文章删除
    @PostMapping(value = "/article/delete")
    @ResponseBody
    public ArticleResponseData delete(@RequestParam int id) {
        try {
            articleServiceImpl.deleteArticleWithId(id);
            logger.info("文章删除成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("文章删除失败，错误信息: " + e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    // 评论删除
    @PostMapping(value = "/comment/delete")
    @ResponseBody
    public ArticleResponseData deleteCommentById(@RequestParam int id) {
        try {
            CommentServiceImpl.deleteCommentById(id);
            logger.info("评论删除成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("评论删除失败，错误信息: " + e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    //向后台评论管理发起页面跳转
    @GetMapping(value = "/comments/toComments/{id}")
    public String toComments(@PathVariable("id") int id, @RequestParam(value = "page", defaultValue = "1") int page,
                             @RequestParam(value = "count", defaultValue = "3") int count, HttpServletRequest request) {
        PageInfo<Comment> pageInfo = CommentServiceImpl.getComments(id, page, count);
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        request.setAttribute("userInfo",user);
        request.setAttribute("comments", pageInfo);
        return "back/Comments";   //跳转页面
    }

    //    content评论更新
    @PostMapping(value = "/comment/update")
    @ResponseBody
    public ArticleResponseData updateComment(@RequestParam int aid, @RequestParam int id, @RequestParam String content, HttpServletRequest request) {

        try {
            CommentServiceImpl.updateCommentById(aid, id, content);
            logger.info("评论更新成功");
            return ArticleResponseData.ok();
        } catch (Exception e) {
            logger.error("评论删除失败，错误信息: " + e.getMessage());
            return ArticleResponseData.fail();
        }
    }

//    request.setAttribute("comments", pageInfo);
//    return "back/Comments";   //跳转页面

    // 跳转到后台评论列表页面
/*    @GetMapping(value = "/comments")
    public String index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "count", defaultValue = "10") int count,
                        HttpServletRequest request) {
        PageInfo<Article> pageInfo = CommentServiceImpl.selectCommentWithPage(page, count);
        request.setAttribute("comments", pageInfo);
        return "back/Comments";
    }*/
}



